//
//  selectInstallmentView.m
//  jiaKaoZhuShou
//
//  Created by 金艺社 on 2018/5/25.
//  Copyright © 2018年 金艺社. All rights reserved.
//

#import "selectInstallmentView.h"
#import "modelinstallment.h"
#import "PaymentFullVC.h"
#import "resultVC.h"
@interface selectInstallmentView () {
    CGFloat Y;
    modelinstallment *selectModel;
}


@end
@implementation selectInstallmentView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor whiteColor];
        Y = 0;
    }
    return self;
}

#pragma mark --- addsubView
- (void)addblackView {
    UIView *blackV = [[UIView alloc]initWithFrame:CGRectMake(0, -(kScreenHeight - 270), kScreenWidth, kScreenHeight - 270)];
    blackV.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    [self addSubview:blackV];
}
- (void)addTitle {
    UILabel *title_lab = [[UILabel alloc]initWithFrame:CGRectMake((kScreenWidth - 150) / 2, Y, 150, 40)];
    title_lab.textAlignment = NSTextAlignmentCenter;
    title_lab.text = @"报名";
    title_lab.font = [UIFont boldSystemFontOfSize:15];
    [self addSubview:title_lab];
}
- (void)addCancleBtn {
    UIButton *cancle = [[UIButton alloc]initWithFrame:CGRectMake(kScreenWidth - 40, Y, 40, 40)];
    [cancle setImage:[UIImage imageNamed:@"cancle"] forState:0];
    [cancle addTarget:self action:@selector(cancleClick) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:cancle];
    Y += 40;
}

- (void)addTuition {
    UILabel *tuition_lab = [[UILabel alloc] initWithFrame:CGRectMake(0, Y, kScreenWidth, 70)];
    tuition_lab.tag = 101;
    tuition_lab.textAlignment = NSTextAlignmentCenter;
    tuition_lab.textColor = [UIColor custom_color:@"#A91E23"];
    tuition_lab.text = @"¥6000.00";
    tuition_lab.font = [UIFont boldSystemFontOfSize:30];
    [self addSubview:tuition_lab];
    Y += 70;
}
- (void)addSelectTuition {
    UILabel *tSelectTuition_lab = [[UILabel alloc] initWithFrame:CGRectMake(20, Y, 150, 30)];
    tSelectTuition_lab.textAlignment = NSTextAlignmentLeft;
    tSelectTuition_lab.text = @"分期 (可选)";
    tSelectTuition_lab.font = [UIFont boldSystemFontOfSize:12];
    [self addSubview:tSelectTuition_lab];
    Y += 30;
}
- (void)addScrollView {
    UIScrollView *backView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, Y, kScreenWidth, 40)];
    backView.tag = 102;
    backView.showsHorizontalScrollIndicator = NO;
    [self addSubview:backView];
    Y += 40 + 15;
    [self addTutionItemWithSuperView:backView];
}
- (void)addTutionItemWithSuperView:(UIScrollView *)supView {
    int itemNumber = (int)self.model.data.count; //个数
    CGFloat interval = 20; // 间距
    CGFloat itemWidth = 115;
    CGFloat itemHight = 40;
    CGFloat contentSizeX = 0.0; // scrollView 可视范围
    for (int i = 0; i < itemNumber; i++) {
        UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(interval + (interval + itemWidth) * i, 0, itemWidth, itemHight)];
        lab.tag =  i;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClick:)];
        [lab addGestureRecognizer:tap]; lab.tag = i;
        lab.backgroundColor = [UIColor groupTableViewBackgroundColor];
        lab.userInteractionEnabled = YES;
        lab.layer.masksToBounds = YES;
        lab.layer.cornerRadius = 5;
        lab.textAlignment = NSTextAlignmentCenter;
        lab.numberOfLines = 2;
        lab.textColor = [UIColor custom_color:@"#000000"];
        lab.text = [NSString stringWithFormat:@"分%d期\n每期%d元", i*3, i*300];
        lab.font = [UIFont systemFontOfSize:12];
        [supView addSubview:lab];
        if (lab.tag == 2) {
            contentSizeX = CGRectGetMaxX(lab.frame);
        }
    }
    supView.contentSize = CGSizeMake(contentSizeX + interval, 0);
}
/**
 两条灰色的线根据传入的 article 进行布局
 @param article 传入添加的是第几条线
 */
- (void)addGrayLineWithArticle:(int)article {
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, article == 1 ? Y : Y, kScreenWidth, 1)];
    line.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self addSubview:line];
    if (article == 2) {
        Y += 15;
    }
}
- (void)addConfirm {
    UIButton *confirm = [[UIButton alloc]initWithFrame:CGRectMake(20, Y, kScreenWidth - 40, 44)];
    confirm.layer.cornerRadius  = 22;
    [confirm setTitle:@"全额付款" forState:0];
    [confirm setTitleColor:[UIColor whiteColor] forState:0];
    confirm.backgroundColor = [UIColor custom_color:@"#A91E23"];
    [confirm addTarget:self action:@selector(confirmClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:confirm];
}

#pragma mark --- clickAction
- (void)cancleClick {
    [self removeFromSuperview];
}
- (void)confirmClick:(UIButton *)sender {
    if ([sender.titleLabel.text isEqualToString:@"全额付款"]) {
       // [self popPaymentFullWithID:@"12"];
        [self generateOrdersRequestWithType:@"1"];
    }else {
        [self generateOrdersRequestWithType:@"2"];
    }
    
}
- (void)tapClick:(UITapGestureRecognizer *)tap {
    UIView *View = tap.view;
    selectModel = [_model.data objectAtIndex:View.tag];
    View.backgroundColor = [UIColor custom_color:@"#A91E23"];
    for (UIView *View in self.subviews) {
        if ([View isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton *)View;
            [btn setTitle:@"分期付款" forState:0];
        }
        if ([View isKindOfClass:[UIScrollView class]]) {
            for (UIView *view in View.subviews) {
                if (view.tag != tap.view.tag) {
                    view.backgroundColor = [UIColor groupTableViewBackgroundColor];
                }
            }
        }
    }
}

#pragma mark --- data
- (void)setModel:(installmentModel *)model {
    _model = model;
    [self addsubView];
    NSArray *subViews = self.subviews;
    for (UIView *view in subViews) {
        if (view.tag == 101) {
            UILabel *moneyLab = (UILabel *)view;
            moneyLab.text = [NSString stringWithFormat:@"¥%@", _model.money];
        }else if (view.tag == 102) {
            NSInteger i = 0;
            for (UIView *subV in view.subviews) {
                if ([subV isKindOfClass:[UILabel class]]) {
                    UILabel *lab = (UILabel *)subV;
                    modelinstallment *modell = [_model.data objectAtIndex:i];
                    lab.text = [NSString stringWithFormat:@"分%@期\n¥%.2f/期", modell.divides, modell.repayMoney.doubleValue];
                    i++;
                }
            }
        }
    }
    
}
- (void)addsubView {
    [self addblackView];
    [self addTitle];
    [self addCancleBtn];
    [self addGrayLineWithArticle:1];
    [self addTuition];
    [self addSelectTuition];
    [self addScrollView];
    [self addGrayLineWithArticle:2];
    [self addConfirm];
}
#pragma mark --- 生成订单
- (void)generateOrdersRequestWithType:(NSString *)type {
    __weak selectInstallmentView *wf = self;
    NSDictionary *dic;
    if ([type isEqualToString:@"1"]) {
        dic = @{
                @"token":USERTOKEN,
                @"money":_model.money,
//                @"repayMoney":selectModel.repayMoney,
                @"repayCount":@"0",
//                @"interest":selectModel.interest,
                @"city":_model.city,
                @"orderFlg":type
                };
    }else {
        dic = @{
                @"token":USERTOKEN,
                @"money":_model.money,
                //                @"repayMoney":selectModel.repayMoney,
                @"repayCount":selectModel.divides,
                //                @"interest":selectModel.interest,
                @"city":_model.city,
                @"orderFlg":type
                };
    }
    
    NSString *url = [NSString stringWithFormat:@"%@%@", [[apiManger shareApiManger] creatOrder], _model.id];
    [networkManger PostHttpDataWithUrlStr:url Dic:dic SuccessBlock:^(id responseObject) {
        
        if ([responseObject[@"rcd"] isEqualToString:R0001]) {
            if ([type isEqualToString:@"1"]) {//全额 订单生成
                [wf popPaymentFullWithID:responseObject[@"orderId"]];
            }else {// 分期 订单生成
                [wf popToResultView:@"1"];
            }
        }else {
            [MBProgressHUD gk_toastShowMessage:responseObject[@"rmg"]];
            [wf popToResultView:@"2"];
        }
        
    } FailureBlock:^(id error) {
        [MBProgressHUD gk_toastShowMessage:@"请求失败"];
    }];
}
- (void)popToResultView:(NSString *)type {// push处理结果页面
    resultVC *VC = [resultVC new];
    VC.resultType = type;
    [[helpPublic getCurrentViewController:self].navigationController pushViewController:VC animated:YES];
    [self removeFromSuperview];
}
- (void)popPaymentFullWithID:(NSString *)ID {//全额去支付
    PaymentFullVC *VC = [PaymentFullVC new];
    VC.ID = ID;
    VC.driveID = _model.id;
    VC.money = _model.money;
    [[helpPublic getCurrentViewController:self].navigationController pushViewController:VC animated:YES];
}
@end
